// 脚本描述文本处理逻辑文件

// 括号定义
export const BRACKETS: Record<string, string> = {
  '(': ')',
  '[': ']',
  '{': '}',
  '<': '>',
  // 中文括号
  '【': '】',
  '《': '》',
  '（': '）',
}

export const RECEIVE_BRACKETS: Record<string, string> = {
  ')': '(',
  ']': '[',
  '}': '{',
  '>': '<',
  // 中文括号
  '】': '【',
  '》': '《',
  '）': '（',
}

// 找到匹配的括号
export const findMatchBracket = (text: string, pos: number) => {
  const char = text[pos]
  const matchChar = BRACKETS[char]
  if (!matchChar) return -1

  const stack = []
  stack.push(char)
  let i = pos + 1
  for (; i < text.length; i++) {
    if (text[i] === char) stack.push(text[i])
    if (text[i] === matchChar) {
      stack.pop()
      if (stack.length === 0) return i
    }
  }
  return -1
}

// 向后查找匹配的括号
export const findMatchBracketBack = (text: string, pos: number) => {
  const char = text[pos]
  const matchChar = RECEIVE_BRACKETS[char]
  if (!matchChar) return -1

  const stack = []
  stack.push(char)
  let i = pos - 1
  for (; i >= 0; i--) {
    if (text[i] === char) stack.push(text[i])
    if (text[i] === matchChar) {
      stack.pop()
      if (stack.length === 0) return i
    }
  }
  return -1
}

// 高亮标记插入
export const defaultHighlightStyleGen = (text: string, startPos: number, endPos: number) => {
  return highlightStyleGen(text, startPos, endPos, 'yellow')
}

export const highlightStyleGen = (text: string, startPos: number, endPos: number, bgColor:string) => {
  if (startPos === -1 || endPos === -1) return null
  return text.slice(0, startPos) + `<span style="background-color: ${bgColor}; border: 1px solid red; padding: 4px 1px;">${text.slice(startPos, endPos + 1)}</span>` + text.slice(endPos + 1)
}

// 全局括号分析 返回第一个不匹配的括号位置，如果括号都匹配则返回 -1
export const globalBracketAnalyze = (text: string): number => {
  const stack: string[] = []
  const posStack: number[] = []

  for (let i = 0; i < text.length; i++) {
    const char = text[i]
    
    // 处理左括号
    if (Object.keys(BRACKETS).includes(char)) {
      stack.push(char)
      posStack.push(i)
      continue
    }
    
    // 闭合左括号
    if (char === BRACKETS[stack[stack.length - 1]]) {
      stack.pop()
      posStack.pop()
      continue
    }

    // 处理右括号
    if (Object.keys(RECEIVE_BRACKETS).includes(char)) {
      // 如果没有对应的左括号，说明这个右括号是多余的
      if (stack.length === 0) {
        return posStack[posStack.length - 1]
      }
      
      // 检查是否与最近的左括号匹配
      const lastBracket = stack[stack.length - 1]
      if (BRACKETS[lastBracket] !== char) {
        return posStack[posStack.length - 1]
      }
      
      stack.pop()
      posStack.pop()
    }
  }

  // 如果还有未匹配的左括号，返回第一个未匹配的位置
  return stack.length > 0 ? posStack[posStack.length - 1] : -1
}

